package cn.sjx.modules.nbiot.handler;

import cn.hutool.core.util.HexUtil;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import cn.sjx.modules.nbiot.entity.common.BusinessBean;
import cn.sjx.modules.nbiot.entity.common.IotProtocolConstants;
import cn.sjx.modules.nbiot.entity.receive.ReceiveBase;
import cn.sjx.modules.nbiot.factory.ReceiveFactory;
import cn.sjx.modules.nbiot.util.SpringBeanUtil;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import org.tio.core.Node;
import org.tio.core.udp.UdpPacket;
import org.tio.core.udp.intf.UdpHandler;

import java.net.DatagramSocket;
import java.net.InetSocketAddress;

/**
 * 已接收信息处理类
 *
 * @Author: sjx
 * @Date: 2019年08月30日 0030 16:52:17
 */
public class ReceiveServerAioHandler implements UdpHandler {

    private static final Log logger = LogFactory.get();

    private SendServerAioHandler sendServerAioHandler = null;

    public ReceiveServerAioHandler() {
        logger.info("======> 自动装配 SendServerAioHandler");
        sendServerAioHandler = SpringBeanUtil.getBean(SendServerAioHandler.class);
    }

    @Override
    public void handler(UdpPacket udpPacket, DatagramSocket datagramSocket) {
        String receiveHexDataStr = null;
        Node remote = null;
        try {
            // 将byte数组转为byteBuffer
            ByteBuf byteBuf = Unpooled.buffer();
            byteBuf.writeBytes(udpPacket.getData());
            int type = byteBuf.getUnsignedByte(IotProtocolConstants.TYPE_ID_INDEX_OF_PACKAGE);

            // 对端Node
            remote = udpPacket.getRemote();
            InetSocketAddress inetSocketAddress = new InetSocketAddress(remote.getIp(), remote.getPort());

            receiveHexDataStr = HexUtil.encodeHexStr(udpPacket.getData(), false);
            logger.info("======> 【地磁|接收|原码】收到来自 {} 的十六进制数据：{}", remote, receiveHexDataStr);

            ReceiveBase receiveBase = ReceiveFactory.createReceiveEntity(type, byteBuf);
            if (null == receiveBase) {
                return;
            }

            sendServerAioHandler.sendData(new BusinessBean(datagramSocket, inetSocketAddress, receiveBase, udpPacket.getData()));
        } catch (Exception e) {
            logger.info("======> 【地磁|接收|数据处理失败】收到来自{}的数据：{}", remote, receiveHexDataStr);
            e.printStackTrace();
        }

    }
}
